#!/usr/bin/env python
# -*- coding: utf-8 -*-
# delimiter separated values

import codecs

class DSV :
    """DSV is Delimiter Separated Values :-)
    
    split(s sep) ; readline and rstrip('\r\n') to extract fields.
    getList() ; field to single list. then '\t'.join(hoge) + '\n' ....
    access field ; fixed[<<fieldname>>}, var[0] to var[n] (n is len(var))
    """
    fixedTitle = None
    fixedMap = {}
    fixed = {}
    var = []
    varTitle = None

    def __init__(self, fixedColumns, varColumns=[]) :
        """ fixed part initialize.

        
        """
        self.setFixedTitle(fixedColumns)
        self.varTitle = varColumns


    def setFixedTitle(self, fixedColumns) :
        self.fixedTitle = fixedColumns
        self.fixedMap = {}
        for i,v in enumerate(self.fixedTitle) :
            self.fixedMap[i] = v
    
    def splitRaw(self, s, sep=u'\t', quote=None) :
        buf = s.split(sep)
        if quote !=  None:
            for i in range(len(buf)) :
                if len(buf[i]) > 1 and buf[i][0] == quote and buf[i][-1] == quote :
                    buf[i] = buf[i][1:-1]
        return buf
        

    def split(self, s, sep=u'\t', quote=None) :
        """split - line to field.

        set linet to s, split by sep.
        Notice: call split, then fixed and var are initialized.
        """
        self.fixed = {}
        self.var = []
        buf = self.splitRaw(s, sep, quote)
        if len(buf) <= len(self.fixedTitle) :
            for i in range(len(buf)) :
                self.fixed[self.fixedMap[i]] = buf[i]
        else :
            for i in range(len(self.fixedTitle)) :
                self.fixed[self.fixedMap[i]] = buf[i]
            for i in range(len(self.fixedTitle), len(buf)) :
                self.var.append(buf[i])
    
    def getList(self) :
        list = []
        for columnName in self.fixedTitle :
            list.append(self.fixed[columnName])
        list.extend(self.var)
        return list

    def getTitle(self) :
        return self.fixedTitle+self.varTitle;

    def clearFixeData(self) :
        self.fixed = {}

    def clearVarData(self, size) :
        self.var = [''] * size

    def clearData(self) :
        self.clearFixed()
        self.clearVar()

    def setVar(self, s) :
        dev.var[tagmap[tag_row['photo_tag']]] = tag_row['photo_tag']

